package by.grsu.crs.database;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

//FIXME: why it is abstract? There are no reason to do it. It should be SINGLETON http://ru.wikipedia.org/wiki/%D0%9E%D0%B4%D0%B8%D0%BD%D0%BE%D1%87%D0%BA%D0%B0_%28%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD_%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F%29#.D0.9F.D1.80.D0.B8.D0.BC.D0.B5.D1.80_.D0.BD.D0.B0_Java_1.6:_.D0.91.D0.B5.D0.B7_.D0.B2.D0.BD.D1.83.D1.82.D1.80.D0.B5.D0.BD.D0.BD.D0.B8.D1.85_.D0.BA.D0.BB.D0.B0.D1.81.D1.81.D0.BE.D0.B2_.28.D0.BB.D0.B5.D0.BD.D0.B8.D0.B2.D0.B0.D1.8F_.D0.BD.D0.B5.D1.81.D0.B8.D0.BD.D1.85.D1.80.D0.BE.D0.BD.D0.B8.D0.B7.D0.B8.D1.80.D0.BE.D0.B2.D0.B0.D0.BD.D0.BD.D0.B0.D1.8F_.D1.80.D0.B5.D0.B0.D0.BB.D0.B8.D0.B7.D0.B0.D1.86.D0.B8.D1.8F.29.
public abstract class ConnectionProvider {
	private static final String JNDI_DB_REF = "java:/comp/env/jdbc/crs";
	private static final String JNDI_DB_REF_NOT_FOUND = "'java:/comp/env/jdbc/crs' is not found in JNDI";

	private static DataSource dataSource;

	// FIXME: it will work. But when you will do a Singleton -place this part of
	// code in constructor
	static {
		try {
			ConnectionProvider.dataSource = (DataSource) new InitialContext().lookup(ConnectionProvider.JNDI_DB_REF);
		} catch (final NamingException e) {
			throw new ExceptionInInitializerError(ConnectionProvider.JNDI_DB_REF_NOT_FOUND);
		}
	}

	public static Connection getConnection() {
		Connection connection = null;
		if (ConnectionProvider.dataSource != null) {
			try {
				connection = ConnectionProvider.dataSource.getConnection();
			} catch (final SQLException e) {
				// TODO: log this and make own exception.
				// FIXME: NO!!! Don't log AND throw exception. You should throw
				// exception OR(!!!) log it.
				e.printStackTrace();
			}
		}

		return connection;
	}
}
